package cn.darkhorse.mesadmin.task;

import cn.darkhorse.common.config.DbTypeConfig;
import cn.darkhorse.common.config.TaskConfig;
import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.device.dao.MqttDataDao;
import cn.darkhorse.device.iot.IotDataAnalyzer;
import cn.darkhorse.device.pojo.MqttData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.darkhorse.device.iot.constant.IotConstant.CACHE_MQTT_DATA_DO_FLAG;
import static cn.darkhorse.device.iot.constant.IotConstant.CACHE_MQTT_DATA_LAST_ID;

/**
 * mqtt 数据解析
 * @since 2023-10-11
 */
@Component("dataTask")
public class IotDataTask {
    private static final Logger log = LoggerFactory.getLogger(IotDataTask.class);
    @Resource
    private IotDataAnalyzer analyzer;

    @Resource
    private MqttDataDao mqttDataDao;

    @Resource
    private RedisCache cache;
    @Resource
    private DbTypeConfig dbTypeConfig;

    /**
     * 从mqtt_data表中拿数据，并解析出相关的参数，存入对应表中
     */
//    @Scheduled(cron = "0/30 * * * * *")
    public void doParse() {
        if(!TaskConfig.isFlag()){
            return;
        }
        UUID uuid = UUID.randomUUID();
        log.debug("开始解析数据" + uuid);
        LocalDateTime begin = LocalDateTime.now();
        // Step.0 获取所有未处理的数据
        Integer lastId = getLastId();
        List<MqttData> mqttDataList = mqttDataDao.getList(Long.parseLong(lastId.toString()));
        log.debug(uuid + " 待处理数据数量：" + mqttDataList.size());
        if (!mqttDataList.isEmpty()){
            mqttDataList.forEach(data -> System.out.println(data.getData()+ "  " + data.getDeviceId()));
            //
            // Step.1 逐条解析
            if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_MYSQL)) {
            //在mysql中执行批量操作
            // 优化速度-20240705
                List<String> sqlList = analyzer.getSql(mqttDataList);
                if (!sqlList.isEmpty()) {
                    mqttDataDao.insertBatchHistoryData(sqlList);
                }
            } else {
                // sql server
                mqttDataList.forEach(data -> {
                    analyzer.analysis(data);
                });
            }
            cache.setCacheObject(CACHE_MQTT_DATA_LAST_ID, mqttDataList.get(mqttDataList.size()-1).getId(),30, TimeUnit.DAYS);
        }


        LocalDateTime end = LocalDateTime.now();
        log.debug("结束解析数据" + uuid + "   耗时：" + calculateTimeDifference(begin,end) + " 毫秒,共处理数据" + mqttDataList.size()+"条");
    }
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    private int getLastId() {
        Object object = cache.getCacheObject(CACHE_MQTT_DATA_LAST_ID);
        if (object != null) {
            return Integer.parseInt(object.toString());
        }else {
            return 0;
        }
    }

    private Long calculateTimeDifference(LocalDateTime begin, LocalDateTime end) {
        Duration duration = Duration.between(begin, end);
        return duration.toMillis();
    }
}
